<?php

namespace App\Services;

use App\Models\AcceptRecord;
use App\Models\WxClient;
use Auth;

class AdminService
{
    const ROLE_SUPER_ADMIN = 1; // 超级管理员
    const ROLE_ADMIN = 2; // 一般后台操作员
    
    protected $_adminUser;

    public function __construct()
    {
        $this->_adminUser = Auth::user();
    }

    public function canShowAdminMenu($_user=null)
    {
        $validUser = $_user ?? $this->_adminUser;
        return $validUser->role == self::ROLE_SUPER_ADMIN;
    }

    public function updateAcceptRecord(array $_filter)
    {
        $is_save = false;
        if (is_array($_filter['projects'])){
            $error_info = "";
            foreach ($_filter['projects'] as $project_id => $customers){
                //判断客户是否已被认领
                foreach ($customers as $key => $customer){
                    $has_record = AcceptRecord::where(['project_id' => $project_id
                        , 'customers' => $customer])
                        ->get()
                        ->pluck('customers')
                        ->all();
                    if (!empty($has_record)){
                         $error_info[$project_id][] = $customer;
                        unset($customers[$key]);
                    }
                }

                //如有未被认领的用户，走认领流程
                if(!empty($customers)){
                    $accept_record = AcceptRecord::where(['project_id' => $project_id
                        , 'user_id' => $_filter['user']])
                        ->first();
                    if (empty($accept_record)){
                        //新建一条record
                        $accept_record = new AcceptRecord();
                        $accept_record->project_id = $project_id;
                        $accept_record->user_id = $_filter['user'];
                        $accept_record->customers = $customers;
                        $accept_record->save();
                        $is_save = true;
                    } else {
                        $accept_record->customers = array_merge($accept_record->customers
                            , $customers);
                        $accept_record->save();
                        $is_save = true;
                    }
                }
            }

            //如有不允许被认领的客户，返回错误信息
//            if (!empty($error_info)){
//                return $error_info;
//            }
            return $is_save;
        }
        return false;
    }

    public static function getCompanyStatus($company_id) {
        //TODO:根据配置文件获取业务线状态
        return [
            '已看房' ,
            '已签约' ,
            '已付款' ,
            '已交房' ,
        ];
    }

    // 项目创建 随机分配一个未使用的微信号
    public function getRandWx() {
        $wx_ids = WxClient::where('project_id', '')->select('id')->get()->pluck('id')->all();
        if (count($wx_ids) != 0) {
            $index = rand(0, count($wx_ids)-1);
            return $wx_ids[$index];
        } else {
            return false;
        }
    }
}